package com.ddf.norman.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ddf.norman.util.HttpClientUtils;
import com.ddf.norman.util.RegexUtils;
import com.ddf.publics.entity.User;
import com.ddf.publics.entity.UserBank;
import com.ddf.publics.entity.UserInfo;
import com.ddf.publics.service.LoginService;
import com.ddf.publics.service.UserBankService;
import com.ddf.publics.service.UserInfoService;
import com.ddf.publics.tool.Constant;
import com.ddf.publics.utils.RedisUtil;
import com.ddf.publics.utils.VerificationCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.Principal;

@Controller
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private UserBankService userBankService;

    //注入redis工具类
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private VerificationCodeUtil verificationCodeUtil;

    /**
     * @description 查询是否有支付密码
     * @author norman
     * @date 2020/7/5 19:21
     * @params [principal]
     * @return java.lang.String
     */
    @ResponseBody
    @PostMapping(value = "/queryIsPayPWD")
    public String queryIsPayPWD(Principal principal) {
        User user = loginService.queryByPhone(principal.getName());
        UserInfo userInfo = userInfoService.userInfoList(user.getId());
        if ("".equals(userInfo.getPayPwd()) || userInfo.getPayPwd() == null) {
            return "PWDUndefined";
        }
        return "success";
    }

    /**
     * @description 发送绑定银行卡的短信验证码
     * @author norman
     * @date 2020/7/5 19:10
     * @params [phone, principal]
     * @return java.lang.String
     */
    @ResponseBody
    @PostMapping(value = "/sendBankVerify")
    public String sendBankVerify(String phone,Principal principal) {
        if (phone == null || "".equals(phone)) {
            return "请输入手机号";
        }
        boolean checkPhone = phone.equals(principal.getName());
        if (checkPhone){
            String code = String.valueOf((int)((Math.random()*9+1)*100000));
            System.out.println("code = " + code);
            String message = verificationCodeUtil.sendCode(phone,VerificationCodeUtil.ALI_TEMPLATE_BINDING_BANK,code);
            if ("OK".equals(message)) {
                redisUtil.set("bankCode:" + phone, code,5 * 60);
            } else {
                System.out.println("message = " + message);
                return "服务器繁忙";
            }
            return "success";
        } else {
            return "手机号错误";
        }

    }

    /**
     * @description 绑定银行卡的请求
     * @author norman
     * @date 2020/7/5 19:21
     * @params [principal, verify, phone, bankNum]
     * @return java.lang.String
     */
    @ResponseBody
    @PostMapping(value = "/bandBank")
    public String bandBank(String verify, String phone ,String bankNum) throws Exception {

        if (bankNum == null) {
            return "银行卡错误";
        } else if (userBankService.queryByNumber(bankNum) != null) {
            return "银行卡已被绑定";
        }

        User user = loginService.queryByPhone(phone);

        if (verify == null || !verify.equals(redisUtil.get("bankCode:" + phone))) {
            return "验证码错误";
        }
        //银行代码请求接口 url
        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo="+bankNum+"&cardBinCheck=true";
        //发送请求，得到 josn 类型的字符串
        String result = HttpClientUtils.get(url);
        // 转为 Json 对象
        JSONObject json = JSON.parseObject(result);
        //获取到 bank 代码
        String bank = String.valueOf(json.get("bank"));
        if (bank==null || "".equals(bank)) {
            return "银行卡号错误";
        }
        //获取银行名称
        String bankJson = Constant.BANK_JSON;
        JSONObject jsonObject = JSONObject.parseObject(bankJson);

        if (jsonObject.get(bank) == null ) {
            return "银行卡号错误";
        }
        //https://apimg.alipay.com/combo.png?d=cashier&t=银行代码
        //存入数据库
        UserBank userBank = new UserBank();
        userBank.setUId(user.getId());
        userBank.setBankCode(bank);
        userBank.setBankName(jsonObject.get(bank).toString());
        userBank.setBankNumber(json.get("key").toString());
        userBankService.insert(userBank);

        return "success";
    }

    /**
     * @description 请求银行卡管理页面
     * @author norman
     * @date 2020/7/5 19:22
     * @params [model, principal]
     * @return java.lang.String
     */
    @GetMapping(value = "/bankSet")
    public String bankSet(Model model, Principal principal) {
        User user = loginService.queryByPhone(principal.getName());
        model.addAttribute("bankList",userBankService.queryAllByUID(user.getId()));
        model.addAttribute("phone",user.getPhone().substring(user.getPhone().length()-4));
        return "userInfo/bankSet";
    }

    /**
     * @description 发送解绑银行卡的短信验证码
     * @author norman
     * @date 2020/7/5 19:22
     * @params [principal]
     * @return java.lang.String
     */
    @ResponseBody
    @PostMapping(value = "/sendDelBank")
    public String sendDelBank(Principal principal) {
        String code = String.valueOf((int)((Math.random()*9+1)*100000));
        System.out.println("code = " + code);
        String message = verificationCodeUtil.sendCode(principal.getName(),VerificationCodeUtil.ALI_TEMPLATE_DE_BINDING_BANK,code);
        if ("OK".equals(message)) {
            redisUtil.set("delBankCode:" + principal.getName(), code,5 * 60);
        } else {
            System.out.println("message = " + message);
            return "服务器繁忙";
        }
        return "success";
    }

    /**
     * @description 解绑银行卡
     * @author norman
     * @date 2020/7/5 19:26
     * @params [principal, code, bId]
     * @return java.lang.String
     */
    @ResponseBody
    @PostMapping(value = "/delBank")
    public String delBank(Principal principal, String code, Integer bId) {
        if (code == null || "".equals(code)) {
            return "请输入验证码";
        }
        if (!code.equals(redisUtil.get("delBankCode:" + principal.getName()))) {
            return "验证码错误";
        }
        userBankService.deleteById(bId);
        return "success";
    }


    /**
     * @description 个人中心总览主页
     * @author norman
     * @date 2020/6/17 8:14
     * @params []
     * @return java.lang.String
     */

    /*
    @GetMapping(value = "/userInfo")
    public String userInfo(){
        return "/userInfo/index";
    }*/

    /**
     * @description 账户设置
     * @author norman
     * @date 2020/6/17 8:14
     * @params []
     * @return java.lang.String
     */

    /*
    @GetMapping(value = "/userSet")
    public String userSet() {
        return "userInfo/userSet";
    }*/

    /**
     * @description 投资记录
     * @author norman
     * @date 2020/6/17 8:15
     * @params []
     * @return java.lang.String
     */

    /*
    @GetMapping(value = "/depositsHistory")
    public String depositsHistory() {
        return "userInfo/depositsHistory";
    }*/

    /**
     * @description 回款计划
     * @author norman
     * @date 2020/6/17 8:15
     * @params []
     * @return java.lang.String
     */

    /*
    @GetMapping(value = "/cashTransfer")
    public String cashTransfer() {
        return "userInfo/cashTransfer";
    }*/

    /**
     * @description 充值
     * @author norman
     * @date 2020/6/17 8:15
     * @params []
     * @return java.lang.String
     */

    /*
    @GetMapping(value = "/recharge")
    public String recharge() {
        return "userInfo/recharge";
    }*/

    /**
     * @description 提现
     * @author norman
     * @date 2020/6/17 8:15
     * @params []
     * @return java.lang.String
     */

    /*
    @GetMapping(value = "/withdraw")
    public String withdraw() {
        return "userInfo/withdraw";
    }*/

    /**
     * @description 红包
     * @author norman
     * @date 2020/6/17 8:23
     * @params []
     * @return java.lang.String
     */
    /*
    @GetMapping(value = "/integral")
    public String integral() {
        return "userInfo/integral";
    }*/

    /**
     * @description 兑换历史
     * @author norman
     * @date 2020/6/17 8:29
     * @params []
     * @return java.lang.String
     */
    /*
    @GetMapping(value = "/changeHistory")
    public String changeHistory() {
        return "userInfo/changeHistory";
    }*/

}
